#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 检查Python环境
echo -e "${YELLOW}检查Python环境...${NC}"
if ! command -v python3 &> /dev/null; then
    echo -e "${RED}错误: 未找到Python3${NC}"
    exit 1
fi

# # 检查虚拟环境
# if [ ! -d "venv" ]; then
#     echo -e "${YELLOW}创建虚拟环境...${NC}"
#     python3 -m venv venv
# fi

# # 激活虚拟环境
# echo -e "${YELLOW}激活虚拟环境...${NC}"
# source venv/bin/activate

# 安装依赖
echo -e "${YELLOW}检查并安装依赖...${NC}"
pip install -r requirements.txt

# 检查端口
PORT=5001
echo -e "${YELLOW}检查端口 ${PORT} 是否可用...${NC}"
if lsof -Pi :$PORT -sTCP:LISTEN -t >/dev/null ; then
    echo -e "${RED}错误: 端口 ${PORT} 已被占用${NC}"
    echo -e "${YELLOW}尝试关闭占用端口的进程...${NC}"
    lsof -ti :$PORT | xargs kill -9
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}成功释放端口 ${PORT}${NC}"
    else
        echo -e "${RED}无法释放端口，请手动关闭占用端口的进程${NC}"
        exit 1
    fi
fi

# 创建必要的目录
echo -e "${YELLOW}检查必要的目录...${NC}"
mkdir -p converted_files
mkdir -p templates

# 启动应用
echo -e "${GREEN}启动应用...${NC}"
echo -e "${YELLOW}应用将在 http://localhost:${PORT} 运行${NC}"
python server.py

# 捕获Ctrl+C
trap 'echo -e "\n${YELLOW}正在关闭应用...${NC}"; deactivate; exit 0' INT 